import api from './api'
import { ElMessage } from 'element-plus'
import { on, off } from "@/utils/dom"

// 授权
export const handleLink = (form, {success} = {}) => {
  const handleMessage = ({ data }) => {
    form = { ...form, ...data }
    if(success && typeof success === 'function') {
      success(data)
    }
    off(window, 'message', handleMessage)
  }
  let win = null
  const handleClose = () => {
    const { shop_id } = form
    if (shop_id) {
      ElMessage.success('更新授权成功')
    } else {
      ElMessage.success('授权成功')
    }
    off(win, 'beforeunload', handleClose)
    win = null
  }
  const { ad_id, auth_area, shop_id, site_ids } = form
  const origin = window.location.origin+'/auth'
  api.link({ origin, ad_id, auth_area, shop_id, site_ids, type: 'amazon' }).then(res => {
    win = window.open(
      res.data.auth_link,
      '_blank',
      'height=700, width=1200, top=200, left=300,toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no'
    )
    on(window, 'message', handleMessage)
    on(win, 'beforeunload', handleClose)
  })
}